package com.xr.blog.tools.security;

import com.xr.blog.exception.CustomException;
import com.xr.blog.pojo.SysUser;
import com.xr.blog.service.SysPermissionService;
import com.xr.blog.service.SysUserService;
import com.xr.blog.tools.text.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author 幸仁杰
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        SysUser user = userService.findByUserName(username);
        //账号验证
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getIsDisable())) {
            log.info("登录用户：{} 已被禁用.", username);
            throw new CustomException("对不起，您的账号：" + username + " 已禁用");
        }
//        List<String> roleCodeList = userService.findRolesByUserName(username);
//
//        List<GrantedAuthority> authorities = roleCodeList.stream().map(e -> new SimpleGrantedAuthority(e)).collect(Collectors.toList());
//
//        UserDetails userDetails = new org.springframework.security.core.userdetails.User(
//                user.getUsername(),user.getPassword(),authorities);
//
//        return userDetails;
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user, permissionService.getMenuPermission(user.getId()));
    }
}
